package com.moma.chatting.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.moma.chatting.dao.ChattingHistoryItem;
import com.moma.chatting.dao.ChattingHistoryItemDao;

public class ConversationRecycler implements Runnable {
	private HashMap<Integer, Conversation> conversationMap;
	private long interval;
	private final static Logger logger;
	static{
		logger = LoggerFactory.getLogger(ConversationRecycler.class);
	}
	public ConversationRecycler(HashMap<Integer, Conversation> conversationMap, long interval){
		this.interval = interval;
		this.conversationMap = conversationMap;
	}
	public void run() {
		logger.info("Recycler is started...");
		while(true){
			logger.info("Recycler is triggered...");
			ArrayList<Integer> conversationIdListNeedBeRemoved = new ArrayList<Integer>();
			for (Conversation conv : this.conversationMap.values()){
				if (conv.getRecyclerFlag()){
					logger.info(String.format("conversation %d is marked as recycle...", conv.getConversationId()));
					ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring-mybatis.xml", "spring-config.xml"});
					ChattingHistoryItemDao d = (ChattingHistoryItemDao)ac.getBean("chattingHistoryItemDao");
					// When set the flag to recyclable, need persist to database.
					// TODO: Jimmy Mo - consider the performance, do not try to convert Message to ChattingHistoryItem.
					List<ChattingHistoryItem> itemList = new ArrayList<ChattingHistoryItem>();
					for (Message msg : conv.getHistoryMessages()){
						ChattingHistoryItem item = new ChattingHistoryItem();
						item.setConversationId(msg.getConversationId());
						item.setContent(msg.getContent());
						item.setSender(msg.getSender().getUniqueName());
						item.setSentWhen(msg.getSentWhen());
						itemList.add(item);
					}
					logger.info("Start to persist...");
					logger.info(String.format("There are %d history message...", itemList.size()));
					d.insertBatch(itemList);
					
					conversationIdListNeedBeRemoved.add(conv.getConversationId());
				}
			}
			// Executes the removal.
			for (int i : conversationIdListNeedBeRemoved){
				
				this.conversationMap.remove(i);
				logger.info(String.format("conversation %d is removed", i));
			}
			try {
				Thread.sleep(interval);
			} catch (Exception e) {
				logger.error("Recycler throws exception..." + e.getStackTrace());
			}
		}
	}
}
